package com.example.springboot_manage.controller;

import com.example.springboot_manage.model.*;
import com.example.springboot_manage.repository.*;
import com.example.springboot_manage.service.AccountService;
import com.example.springboot_manage.service.CategoryService;
import com.example.springboot_manage.service.ManageService;
import com.example.springboot_manage.util.CookieUtil;
import com.example.springboot_manage.util.ResultUtil;
import com.example.springboot_manage.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/manage")
public class ManageHandler {

    @Autowired
    private ShoeInfoRepository shoeInfoRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SpecsInfoRepository specsInfoRepository;

    @Autowired
    private SpecsColorRepository specsColorRepository;

    @Autowired
    private SpecsSizeRepository specsSizeRepository;

    @Autowired
    private AccountService accountService;




    /**
     * 对商品信息的增删改查
     */
    @RequestMapping("/shoeInfo")
    public ResultVO findShoeInfo(@RequestParam("page") String page, @RequestParam("limit") String limit){
        Map<String,Object> map = manageService.findShoeInfo(page,limit);
        List<ShoeInfo> shoeInfos = (List<ShoeInfo>) map.get("lists");
        int count = (int) map.get("count");
        return ResultUtil.success(shoeInfos,count);
    }

    @RequestMapping("/delShoeInfo")
    public String delShoeInfo(@RequestParam("id") String shoeId){
        int id = Integer.parseInt(shoeId);
        int flag = shoeInfoRepository.deleteById(id);
        if (flag != 0){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/updateShoeInfo")
    public String updateInfo(@RequestParam("shoeId") String shoeId,
                             @RequestParam("shoeName") String shoeName,
                             @RequestParam("shoePrice") String shoePrice,
                             @RequestParam("shoeDescription") String shoeDescription,
                             @RequestParam("shoeStock") String shoeStock,
                             @RequestParam("shoeIcon") String shoeIcon,
                             @RequestParam("categoryType") String categoryType) {
        int id = Integer.parseInt(shoeId);
        ShoeInfo shoeInfo = new ShoeInfo();
        shoeInfo.setShoeId(id);
        shoeInfo.setShoeName(shoeName);
        shoeInfo.setShoeIcon(shoeIcon);
        shoeInfo.setShoeDescription(shoeDescription);
        shoeInfo.setShoePrice(shoePrice);
        shoeInfo.setShoeStock(shoeStock);
        shoeInfo.setCategoryType(Integer.parseInt(categoryType));
        int flag = shoeInfoRepository.update(shoeInfo);
        if (flag > 0) {
            return "true";
        } else {
            return "false";
        }
    }

    @RequestMapping("/saveShoeInfo")
    public String saveCategory(@RequestParam("shoeName") String shoeName,
                               @RequestParam("shoePrice") String shoePrice,
                               @RequestParam("shoeDescription") String shoeDescription,
                               @RequestParam("shoeStock") String shoeStock,
                               @RequestParam("shoeIcon") String shoeIcon,
                               @RequestParam("categoryType") String categoryType){
        ShoeInfo shoeInfo = new ShoeInfo();
        shoeInfo.setShoeName(shoeName);
        shoeInfo.setShoeIcon(shoeIcon);
        shoeInfo.setShoeDescription(shoeDescription);
        shoeInfo.setShoePrice(shoePrice);
        shoeInfo.setShoeStock(shoeStock);
        shoeInfo.setCategoryType(Integer.parseInt(categoryType));
        int flag = shoeInfoRepository.save(shoeInfo);
        if (flag > 0) {
            return "true";
        } else {
            return "false";
        }
    }


    /**
    对商户的增删改查
     **/
    @RequestMapping("/category")
    public ResultVO findCategory(){
        Map<String,Object> map = manageService.findCategory();
        List<ShoeCategory> categories = (List<ShoeCategory>) map.get("lists");
        int count = (int) map.get("count");
        return ResultUtil.success(categories,count);
    }

    @RequestMapping("/delCategory")
    public String delCategory(@RequestParam("id") String categoryId){
        int id = Integer.parseInt(categoryId);
        int flag = categoryService.delCategory(id);
        if (flag != 0){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/updateCategory")
    public String updateCategory(@RequestParam("categoryId") String categoryId,
                                 @RequestParam("categoryName") String categoryName,
                                 @RequestParam("categoryType") String categoryType,
                                 @RequestParam("introduce") String introduce) {
        int id = Integer.parseInt(categoryId);
        ShoeCategory category = new ShoeCategory();
        category.setCategoryId(id);
        category.setCategoryName(categoryName);
        category.setIntroduce(introduce);
        category.setCategoryType(Integer.parseInt(categoryType));
        int flag = categoryService.updateCategory(category);
        if (flag > 0) {
            return "true";
        } else {
            return "false";
        }
    }

    @RequestMapping("/saveCategory")
    public String saveCategory(@RequestParam("categoryName") String categoryName,
                               @RequestParam("categoryType") String categoryType,
                               @RequestParam("introduce") String introduce){
        ShoeCategory category = new ShoeCategory();
        category.setCategoryName(categoryName);
        category.setIntroduce(introduce);
        category.setCategoryType(Integer.parseInt(categoryType));
        int flag = categoryService.saveCategory(category);
        if (flag > 0) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * 对订单的删改查
     */
    @RequestMapping("/orderMaster")
    public ResultVO findOrder(@RequestParam("page") String page, @RequestParam("limit") String limit){
        int pageSize = Integer.parseInt(limit);
        int startIndex = (Integer.parseInt(page) - 1) * pageSize;
        List<OrderMaster> orderMasters = orderMasterRepository.findAll(startIndex,pageSize);
        int count = orderMasterRepository.queryAllCount();
        return ResultUtil.success(orderMasters,count);
    }

    @RequestMapping("/delOrderMaster")
    public String delOrderMaster(@RequestParam("id") String orderId){
        int id = Integer.parseInt(orderId);
        int flag = orderMasterRepository.deleteById(id);
        if (flag != 0){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/updateOrderMaster")
    public String updateOrderMaster(@RequestParam("orderId") String orderId,
                             @RequestParam("buyerName") String buyerName,
                             @RequestParam("buyerPhone") String buyerPhone,
                             @RequestParam("buyerAddress") String buyerAddress,
                             @RequestParam("shoeId") String shoeId,
                             @RequestParam("shoeName") String shoeName,
                             @RequestParam("shoeQuantity") String shoeQuantity,
                             @RequestParam("shoeIcon") String shoeIcon,
                             @RequestParam("specsId") String specsId,
                             @RequestParam("specsNameColor") String specsNameColor,
                             @RequestParam("specsNameSize") String specsNameSize,
                             @RequestParam("specsPrice") String specsPrice,
                             @RequestParam("orderAmount") String orderAmount,
                             @RequestParam("payStatus") String payStatus,
                             @RequestParam("categoryType") String categoryType) {
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(new BigDecimal(orderAmount));
        orderMaster.setBuyerAddress(buyerAddress);
        orderMaster.setShoeIcon(shoeIcon);
        orderMaster.setShoeId(Integer.parseInt(shoeId));
        orderMaster.setShoeName(shoeName);
        orderMaster.setBuyerPhone(buyerPhone);
        orderMaster.setShoeQuantity(shoeQuantity);
        orderMaster.setSpecsId(Integer.parseInt(specsId));
        orderMaster.setSpecsNameColor(specsNameColor);
        orderMaster.setSpecsNameColor(specsNameColor);
        orderMaster.setSpecsNameSize(specsNameSize);
        orderMaster.setSpecsPrice(new BigDecimal(specsPrice));
        orderMaster.setPayStatus(Integer.parseInt(payStatus));
        orderMaster.setBuyerName(buyerName);
        orderMaster.setCategoryType(Integer.parseInt(categoryType));
        int flag = orderMasterRepository.update(orderMaster);
        System.out.println(orderMaster);
        if (flag > 0) {
            return "true";
        } else {
            return "false";
        }
    }

    /*
    对规格的crud
     */
    @RequestMapping("/specsInfo")
    public ResultVO specsInfo(@RequestParam("page") String page, @RequestParam("limit") String limit){
        int pageSize = Integer.parseInt(limit);
        int startIndex = (Integer.parseInt(page) - 1) * pageSize;
        List<SpecsInfo> specsInfo = specsInfoRepository.findAll(startIndex,pageSize);
        int count = specsInfoRepository.queryAllCount();
        return ResultUtil.success(specsInfo,count);
    }

    @RequestMapping("/delSpecsInfo")
    public String delSpecsInfo(@RequestParam("id") String specsId){
        int id = Integer.parseInt(specsId);
        int flag = specsInfoRepository.deleteById(id);
        if (flag != 0){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/updateSpecsInfo")
    public String updateSpecsInfo(@RequestParam("specsId") String specsId,
                                 @RequestParam("specsNameSize") String specsNameSize,
                                  @RequestParam("specsNameColor") String specsNameColor,
                                  @RequestParam("shoeId") String shoeId,
                                  @RequestParam("specsStock") String specsStock,
                                  @RequestParam("specsPrice") String specsPrice,
                                  @RequestParam("categoryType") String categoryType) {
        SpecsInfo specsInfo = new SpecsInfo();
        specsInfo.setSpecsId(Integer.parseInt(specsId));
        specsInfo.setSpecsNameSize(specsNameSize);
        specsInfo.setSpecsNameColor(specsNameColor);
        specsInfo.setShoeId(Integer.parseInt(shoeId));
        specsInfo.setSpecsPrice(specsPrice);
        specsInfo.setSpecsStock(Integer.parseInt(specsStock));
        specsInfo.setCategoryType(Integer.parseInt(categoryType));
        SpecsColor specsColor = specsColorRepository.findByColorName(specsNameColor,Integer.parseInt(shoeId));
        SpecsSize specsSize = specsSizeRepository.findBySizeName(specsNameSize);
        if (specsColor != null && specsSize != null){
            specsInfo.setSpecsIdColor(specsColor.getSpecsId());
            specsInfo.setSpecsIdSize(specsSize.getSpecsId());
            int flag = specsInfoRepository.update(specsInfo);
            if (flag > 0) {
                return "true";
            } else {
                return "false";
            }
        }else {
            return "false";
        }



    }

    @RequestMapping("/saveSpecsInfo")
    public String saveSpecsInfo(@RequestParam("specsNameSize") String specsNameSize,
                                @RequestParam("specsNameColor") String specsNameColor,
                                @RequestParam("shoeId") String shoeId,
                                @RequestParam("specsStock") String specsStock,
                                @RequestParam("specsPrice") String specsPrice,
                                @RequestParam("categoryType") String categoryType){
        SpecsInfo specsInfo = new SpecsInfo();
        specsInfo.setSpecsNameSize(specsNameSize);
        specsInfo.setSpecsNameColor(specsNameColor);
        specsInfo.setShoeId(Integer.parseInt(shoeId));
        specsInfo.setSpecsPrice(specsPrice);
        specsInfo.setSpecsStock(Integer.parseInt(specsStock));
        specsInfo.setCategoryType(Integer.parseInt(categoryType));
        SpecsSize specsSize = specsSizeRepository.findBySizeName(specsNameSize);
        SpecsColor specsColor = specsColorRepository.findByColorName(specsNameColor,Integer.parseInt(shoeId));
        specsInfo.setSpecsIdColor(specsColor.getSpecsId());
        specsInfo.setSpecsIdSize(specsSize.getSpecsId());
        if (specsColor != null && specsSize != null){
            specsInfo.setSpecsIdColor(specsColor.getSpecsId());
            specsInfo.setSpecsIdSize(specsSize.getSpecsId());
            int flag = specsInfoRepository.save(specsInfo);
            if (flag > 0) {
                return "true";
            } else {
                return "false";
            }
        }else {
            return "false";
        }
    }

    /*
    对规格颜色的crud
     */
    @RequestMapping("/specsColor")
    public ResultVO specsColor(@RequestParam("page") String page, @RequestParam("limit") String limit){
        int pageSize = Integer.parseInt(limit);
        int startIndex = (Integer.parseInt(page) - 1) * pageSize;
        List<SpecsColor> specsColors = specsColorRepository.findAll(startIndex,pageSize);
        int count = specsColorRepository.queryAllCount();
        return ResultUtil.success(specsColors,count);
    }

    @RequestMapping("/delSpecsColor")
    public String delSpecsColor(@RequestParam("id") String specsId){
        int id = Integer.parseInt(specsId);
        int flag = specsColorRepository.deleteById(id);
        if (flag != 0){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/updateSpecsColor")
    public String updateSpecsColor(@RequestParam("specsId") String specsId,
                                  @RequestParam("specsName") String specsName,
                                  @RequestParam("shoeId") String shoeId,
                                  @RequestParam("specsIcon") String specsIcon,
                                  @RequestParam("specsPreview") String specsPreview,
                                  @RequestParam("categoryType") String categoryType) {
        SpecsColor specsColor = new SpecsColor();
        specsColor.setSpecsId(Integer.parseInt(specsId));
        specsColor.setSpecsName(specsName);
        specsColor.setShoeId(Integer.parseInt(shoeId));
        specsColor.setSpecsIcon(specsIcon);
        specsColor.setSpecsPreview(specsPreview);
        specsColor.setCategoryType(Integer.parseInt(categoryType));
        SpecsColor specsColor1 = specsColorRepository.findByColorName(specsName,Integer.parseInt(shoeId));
        if (specsColor1 == null || (specsColor1 != null && specsColor1.getSpecsId() == specsColor.getSpecsId())){
            int flag = specsColorRepository.update(specsColor);
            if (flag > 0) {
                return "true";
            } else {
                return "false";
            }
        }else{
            return "false";
        }
    }

    @RequestMapping("/saveSpecsColor")
    public String saveSpecsColor(@RequestParam("specsName") String specsName,
                                 @RequestParam("shoeId") String shoeId,
                                 @RequestParam("specsIcon") String specsIcon,
                                 @RequestParam("specsPreview") String specsPreview,
                                 @RequestParam("categoryType") String categoryType){
        SpecsColor specsColor = new SpecsColor();
        specsColor.setSpecsName(specsName);
        specsColor.setShoeId(Integer.parseInt(shoeId));
        specsColor.setSpecsIcon(specsIcon);
        specsColor.setSpecsPreview(specsPreview);
        specsColor.setCategoryType(Integer.parseInt(categoryType));
        SpecsColor specsColor1 = specsColorRepository.findByColorName(specsName,Integer.parseInt(shoeId));
        if (specsColor1 == null){
            int flag = specsColorRepository.save(specsColor);
            if (flag > 0){
                return "true";
            }else{
                return "false";
            }
        }else{
            return "false";
        }
    }

    /*
    对规格尺码的crud
     */
    @RequestMapping("/specsSize")
    public ResultVO specsSize(@RequestParam("page") String page, @RequestParam("limit") String limit){
        int pageSize = Integer.parseInt(limit);
        int startIndex = (Integer.parseInt(page) - 1) * pageSize;
        List<SpecsSize> specsSizes = specsSizeRepository.findAll(startIndex,pageSize);
        int count = specsSizeRepository.queryAllCount();
        return ResultUtil.success(specsSizes,count);
    }

    @RequestMapping("/delSpecsSize")
    public String delSpecsSize(@RequestParam("id") String specsId){
        int id = Integer.parseInt(specsId);
        int flag = specsSizeRepository.deleteById(id);
        if (flag != 0){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/updateSpecsSize")
    public String updateSpecsSize(@RequestParam("specsId") String specsId,
                                   @RequestParam("specsName") String specsName) {
        SpecsSize specsSize = new SpecsSize();
        specsSize.setSpecsId(Integer.parseInt(specsId));
        specsSize.setSpecsName(specsName);
        SpecsSize specsSize1 = specsSizeRepository.findBySizeName(specsName);
        if (specsSize1 == null || (specsSize1 != null && specsSize1.getSpecsId() == specsSize.getSpecsId())){
            int flag = specsSizeRepository.update(specsSize);
            if (flag > 0) {
                return "true";
            } else {
                return "false";
            }
        }else{
            return "false";
        }
    }

    @RequestMapping("/saveSpecsSize")
    public String saveSpecsSize(@RequestParam("specsName") String specsName){
        SpecsSize specsSize = new SpecsSize();
        specsSize.setSpecsName(specsName);
        SpecsSize specsSize1 = specsSizeRepository.findBySizeName(specsName);
        if (specsSize1 == null){
            int flag = specsSizeRepository.save(specsSize);
            if (flag > 0){
                return "true";
            }else{
                return "false";
            }
        }else{
            return "false";
        }
    }

    @Autowired
    private BulletinRepository bulletinRepository;

    //发布页面
    @RequestMapping("/saveBulletin")
    public Map addBulletin(@RequestParam("title") String title,
                              @RequestParam(value = "content",required = false) String content) {
        Map<String,Object> map = new HashMap();
        Bulletin bulletin = new Bulletin();
        if (title==null || title.equals("")){
            map.put("code",1);
            return map;
        }
        bulletin.setTitle(title);
        bulletin.setContent(content);
        int flag = bulletinRepository.save(bulletin);
        if (flag > 0) {
            map.put("code",0);
            Bulletin bulletin1 = bulletinRepository.findByTitle(title);
            map.put("id",bulletin1.getId());
            return map;
        }
        map.put("code",1);
        return map;
    }

    @RequestMapping("/findTitles")
    public List<String> findTitles(){
        List<String> titles = bulletinRepository.findTitles();
        return titles;
    }

    //获取标题返回数据
    @RequestMapping("/findBulletin")
    public Bulletin findBulletin(@RequestParam("title")String title){
        Bulletin bulletin = bulletinRepository.findByTitle(title);
        return bulletin;
    }

    @RequestMapping("/findBulletinInfo")
    public ResultVO findBulletinInfo(@RequestParam("page") String page, @RequestParam("limit") String limit){
        int pageSize = Integer.parseInt(limit);
        int startIndex = (Integer.parseInt(page) - 1) * pageSize;
        List<Bulletin> bulletins = bulletinRepository.findAll(startIndex,pageSize);
        int count = bulletinRepository.queryAllCount();
        return ResultUtil.success(bulletins,count);
    }



    //删除标题对应的页面
    @RequestMapping("/delPage")
    public String delPage(@RequestParam("title")String title){
        int flag = bulletinRepository.deleteById(title);
        if (flag>0){
            return "true";
        }
        return null;
    }

    @Autowired
    public AccountRepository accountRepository;
    //上传图片
    @RequestMapping("/upload")
    public ResultVO upload(@RequestParam("file")MultipartFile file, HttpSession session){
        if (file.isEmpty()){
            return ResultUtil.error("文件为空");
        }
        //获取文件名
        String originalFileName = file.getOriginalFilename();
        String fileName = System.currentTimeMillis()+"_"+originalFileName;
        //获取路径
        String path = getPath();
        //创建新的文件
        File fileMkdir = new File(path+"\\"+fileName);
        if (!fileMkdir.exists()){
            fileMkdir.mkdir();
        }
        String oldFileName = accountService.updateImages(fileName,session);

        File file1 = new File(path);

        try{
            file.transferTo(fileMkdir);
            File[] files = file1.listFiles();
            for (File f:files){
                if (oldFileName.equals(f.getName())){
                    f.delete();
                }
            }

            return ResultUtil.success01(fileName);
        }catch (IOException e){
            e.printStackTrace();
            return ResultUtil.error("上传失败！");
        }

    }

    //获取存储位置
    private String getPath(){
        String c = System.getProperty("user.dir");
        return c+"\\src\\main\\resources\\static\\images"+"\\";
    }

    @RequestMapping("/updatePersonInfo")
    public String updatePersonInfo(Account account, HttpServletRequest request, HttpServletResponse response,
                                   HttpSession session){
//        Account account = new Account();
//        Account account1 = (Account) session.getAttribute("loginInfo");
//        account.setId(account1.getId());
//        account.setEmail(email);
//        account.setNickname(nickname);
//        account.setPhone(phone);
//        account.setRemarks(remarks);
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        Account account1 = accountService.updatePersonInfo(account,ticket);
        if (account1!=null){
//            Account account2 = new Account();
//            account2 = accountRepository.findByUsername(account.getUsername());
            session.removeAttribute("loginInfo");
            session.setAttribute("loginInfo",account1);
            return "true";
        }else{
            return "false";
        }
    }

    @Autowired
    public ManageService manageService;

    @RequestMapping("/searchShoeInfo")
    public ResultVO searchShoeInfo(@RequestParam("page") String page,
                                   @RequestParam("limit") String limit,
                                   @RequestParam(value = "shoeId") String shoeId,
                                   @RequestParam(value = "shoeName") String shoeName,
                                   @RequestParam(value = "shoeDescription") String shoeDescription){

        int pageSize = Integer.parseInt(limit);
        int startIndex = (Integer.parseInt(page) - 1) * pageSize;
        System.out.println(shoeId+shoeName+shoeDescription);
        List<ShoeInfo> shoeList = manageService.findBySearchId(startIndex,pageSize,shoeId,shoeName,shoeDescription);
        int count = manageService.queryCountById(shoeId,shoeName,shoeDescription);
        System.out.println(ResultUtil.success(shoeList,count));
        return ResultUtil.success(shoeList,count);
    }

    @RequestMapping("/updatePassWord")
    public Map updatePassword(@RequestParam("oldPassword") String oldPassword,
                                   @RequestParam("password") String password,
                                   @RequestParam("repassword") String repassword,
                                   HttpSession session,Model model){
        Account account = (Account) session.getAttribute("loginInfo");
        int id = account.getId();
        Map<String,Object> map = manageService.updatePassword(oldPassword,password,repassword,id);

        return map;
    }

}
